<?php
/**
 * RedXenon Framework
 * 
 * LICENSE
 * 
 * This source file is subject to the New BSD license that is bundled
 * with this package in the file LICENSE.txt
 * A copy of this license can be found in the world-wide-web at this URL:
 * http://www.redxenon.com/license/new-bsd-license.txt
 *
 * RedXenon Curl (RXCurl.php)
 * Defines a curl interface to configure and manage the behaviour 
 * of HTTP requests though the PHP Curl Extension
 * 
 * IMPORTANT: The PHP Curl Extension must be installed in your
 * system in order to be able to use this class  
 * 
 * @category RedXenon
 * @package RedXenon_Curl
 * @copyright Copyright (c) 2012 Red Xenon (http://www.redxenon.com)
 * @version $Id: RXCurl.php 1.0 2012-06-02 $ 
 */
class RXCurl{
	
	private $curl;
	private $bufferSize;
	private $post;
	private $returnTransfer;
	private $timeout;
	private $headers;
	private $response;
	private $content;
	private $info;
	
	public function __construct($url){
		try{
			$this->curl = curl_init();
			curl_setopt($this->curl, CURLOPT_URL, $url);
			curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, TRUE);

			/*
			 *  Some servers (like Lighttpd) don't process the curl requests properly
			 * This makes the trick as read on:
			 * http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers
			 */
			curl_setopt($this->curl, CURLOPT_HTTPHEADER, array("Expect:"));
			
		}catch(Exception $e){
			throw new Exception("Error on creating Curl Instance: ".$e->getMesage());	
		}
	}
	
	public function setPost(){
		$this->post = TRUE;
	}
	
	public function setBufferSize($size){
		$this->bufferSize = $size;
	}
	
	public function setReturnTransfer(){
		$this->returnTransfer = TRUE;
	}
	
	public function setTimeout($timeout){
		$this->timeout = $timeout;
	}
	
	public function getResponse(){
		return $this->response;
	}
	
	public function getHeaders(){
		return $this->headers;
	}
	
	public function getInfo(){
		return $this->info;
	}
	
	public function getContent(){
		return $this->content;
	}
	
	public function execute(){
		if($this->post)
			curl_setopt($this->curl, CURLOPT_POST, 1);
		if($this->returnTransfer)
			curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
		if($this->bufferSize && is_numeric($this->bufferSize))
			curl_setopt($this->curl, CURLOPT_BUFFERSIZE, $this->bufferSize);
		if($this->timeout && is_numeric($this->timeout))
			curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, $this->timeout);
		
		$this->response = curl_exec($this->curl);

		if($this->response){
		
			$this->info = curl_getinfo($this->curl);
			curl_close($this->curl);
			$this->headers = substr($this->response, 0, $this->info['header_size']);
			$this->content = substr($this->response, 0, -$this->info['download_content_length']);
			return TRUE;
		}else{
			curl_close($this->curl);
			return FALSE;
		}
	}
}
?>     }